package spoon.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import spoon.common.exception.ConnectionException;

@Service
public class HttpServiceImpl implements HttpService {

	/**
	 * url 주소를 URLConnection 형태로 변경한다.
	 * 
	 * @param urlString
	 * @return
	 */
	private URLConnection getUrlConnection(String urlString) {
		URL url;
		URLConnection connection = null;
		try {
			url = new URL(urlString);
			connection = url.openConnection();
			connection.setDoOutput(true);
		} catch (MalformedURLException e) {
			throw new ConnectionException(e);
		} catch (IOException e) {
			throw new ConnectionException(e);
		}

		return connection;
	}

	@Override
	public String getSource(String url) {
		URLConnection connection = this.getUrlConnection(url);
		return this.getSource(connection);
	}

	@Override
	public String getSource(URLConnection connection) {
		BufferedReader in = null;
		StringBuffer sb = new StringBuffer();
		try {
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				sb.append(line);
			}
		} catch (UnsupportedEncodingException e) {
			throw new ConnectionException(e);
		} catch (IOException e) {
			throw new ConnectionException(e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					throw new ConnectionException(e);
				}
			}
		}
		return sb.toString();
	}

	@Override
	public Elements getElement(String url, String selector) {
		Document doc = null;
		try {
			doc = Jsoup.connect(url).timeout(10000).get();
		} catch (IOException e) {
			throw new ConnectionException(e);
		}
		return doc.select(selector);
	}

	@Override
	public String getJavascript(String url) {
		Document doc = null;
		
		try {
			doc = Jsoup.connect(url).ignoreContentType(true).get();
		} catch (IOException e) {
			throw new ConnectionException(e);
		}
		
		return doc.html();
	}

}
